﻿using AutoMapper;
using BaseData.API.Write.Applications.Commands;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Write.Applications.CommandHandlers
{
    /// <summary>
    /// 添加角色配置角色--处理命令
    /// </summary>
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<UserRoleRelation> userRoleRep;
        private readonly ILogger<AddUserCommandHandler> logger;
        private readonly IMapper mapper;

        public AddUserCommandHandler(IBaseRepository<User> userRep,IBaseRepository<UserRoleRelation> userRoleRep,ILogger<AddUserCommandHandler> logger,IMapper mapper)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            var count = await userRep.GetAll().CountAsync(x => x.UserName == request.UserName);
            if (count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.添加失败,
                    Message = "该用户名已存在!!!",
                    Data = -1
                };
            }
            ApiResult<int> result = new ApiResult<int>();
            result.Code=ApiEnum.添加成功;
            result.Message=ApiEnum.添加成功.ToString();

            using(var tran=userRep.DB.Database.BeginTransaction())
            {
                try
                {
                    var entity = mapper.Map<User>(request);
                    entity.Status=false;
                    entity.CreateTime=DateTime.Now;
                    entity.UserPass=request.UserPass.GetMD5();
                    await userRep.AddAsync(entity);

                    //添加用户角色中间
                    var list=new  List<UserRoleRelation>();
                    foreach (var item in request.RoleIds)
                    {
                        list.Add(new UserRoleRelation()
                        {
                            UserId = entity.UserId,
                            RoleId=item
                        });
                    }
                    await userRoleRep.AddRange(list);
                    //提交
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError("=>" + ex.Message);
                    result.Code = ApiEnum.添加失败;
                    result.Message = ApiEnum.添加失败.ToString()+ex.Message;
                    //回滚
                    tran.Rollback();
                }
            }

            return await Task.FromResult(result);
        }
    }
}
